package _0_Xorm框架

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
	"xorm.io/xorm"
)

var engine *xorm.Engine
var err error

func init() {
	//连接数据库
	engine, err := xorm.NewEngine("mysql", "root:123456@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4")
	engine.SetMaxIdleConns(10)                //连接池的空闲数大小
	engine.SetMaxOpenConns(5)                 //最大打开连接数
	engine.SetConnMaxLifetime(time.Hour * 24) //连接的最大生存时间

	if err != nil {
		fmt.Printf("xorm数据库连接失败：%v\n", err)
		return
	} else {
		err := engine.Ping()
		if err != nil {
			fmt.Printf("连接成功，ping失败:%v\n", err)
		} else {
			fmt.Println("连接成功，ping通了...")
		}
	}

	//创建表
	type User struct {
		Id      uint
		Name    string
		Salt    string
		Age     uint8
		Passwd  string    `xorm:"varchar(200)"`
		Created time.Time `xorm:"created"`
		Updated time.Time `xorm:"updated"`
	}
	err2 := engine.Sync(new(User))
	if err2 != nil {
		fmt.Println("创建表失败:", err2)
	} else {
		fmt.Println("创建表成功:", err2)
	}

	//添加数据
	user := User{
		Id:      1,
		Name:    "打盹",
		Salt:    "哈哈",
		Age:     19,
		Passwd:  "abc123",
		Created: time.Time{},
		Updated: time.Time{},
	}
	insert, _ := engine.Insert(&user) //返回的是成功插入数据的行数，数量
	fmt.Println("插入数据成功：", insert)

}
